<template>
  <page-wrap back hide-tab :title="oppInfo.name || '聊天'" stay-still :hideSafeArea="true">
    <template slot="title">
      <view v-if="isAdviser" class="adviser-title">{{ adviser.nickName }}
        <view class="adviser-role" @click="handleAdviserRole">
          {{ adviser.role }}
          <u-icon size="20" :name="showRole ? 'arrow-up' : 'arrow-down'"></u-icon>
        </view>
      </view>
      <template v-else>
        <view class="u-text-center">{{ oppInfo.name }}</view>
        <view class="u-text-center nav-job">{{ jobData && jobData.jtzw }}</view>
      </template>
    </template>
    <view class="chat">
      <scroll-view class="chat-list" id="chat-list" ref="chatList" scroll-y upper-threshold="1"
        :scroll-into-view="toLast" @scrolltoupper="handleMore">
        <u-loadmore class="list-more" :status="moreLoading" :load-text="loadText" />
        <view class="chat-item" v-for="(item, index) in chatList" :key="index" :id="'item' + (index + 1)">
          <view class="item-time" v-if="item.showTime">{{
            item.timeParse
          }}</view>
          <!-- 对方 -->
          <view :class="{'item-opp': item.flow == 'in', 'item-self': item.flow != 'in'}" data-type="unread" :data-item="item">
            <image v-if="item.flow == 'in'" class="item-avatar" :src="oppInfo.avatar" @click="handleClickAvatar(item)"></image>
            <view class="item-content" v-html="changeToEmoji(item.payload.text)"
              v-if="item.type == TencentCloudChat.TYPES.MSG_TEXT"></view>
            <view class="item-content image" v-else-if="item.type == TencentCloudChat.TYPES.MSG_IMAGE">
              <image v-if="item.payload.imageInfoArray" :src="item.payload.imageInfoArray[1].url" mode="widthFix"
                @click="handlePreviewImage(item.payload.imageInfoArray[0].url)"></image>
            </view>
            <view class="item-content item-file" v-else-if="item.type == TencentCloudChat.TYPES.MSG_FILE"
              @click="handleFileClick(item.payload)">
              <text class="icon icon-file"></text>
              <view class="file-name u-line-2">
                {{ item.payload.fileName }}
              </view>
            </view>
            
            <view class="item-content" v-else>
              请在APP内查看此类型消息
            </view>
            <image v-if="item.flow == 'out'" class="item-avatar" :src="selfInfo.pic" @click="handleClickAvatar(item)"></image>
          </view>
        </view>
      </scroll-view>
      <view class="chat-send-wrap" :style="'padding-bottom:calc(' + inputBottom + 'px + 24rpx)'">
        <view class="chat-send">
          <view class="chat-send-left" @click="handleShowCommonTerms">
            <text v-if="showCommonTerms" class="icon icon-keyboard"></text>
            <text v-else class="btn btn-common-terms">常用语</text>
          </view>
          <my-textarea :class="['chat-input', lines]" :value.sync="sendText" :replace="false" :clearDisabled="true"
            :focus.sync="inputFocus" :holdKeyboard="true" placeholder="请输入聊天内容" @board-change="handleBoardChange"
            @line-change="handleLinechange"></my-textarea>
          <view @click="handleSendModeClick">
            <!-- <text v-if="sendMode == 'text'" class="icon icon-emoji"></text> -->
            <text v-if="sendMode == 'emoji'" class="icon icon-keyboard"></text>
          </view>
          <view v-show="sendText" @click="handleSendMsg">
            <text class="icon icon-send"></text>
          </view>
          <view v-show="!sendText" @click="handleMoreSendClick">
            <text class="icon icon-add"></text>
          </view>
        </view>
        <!-- 卡片 -->
        <view v-if="moreSendVisible" class="more-send">
          <template v-if="!showCloseService">
            <view class="more-send-item" @click="handleSendPic">
              <image class="img" :src="img"></image>
              <text>图片</text>
            </view>
            <view class="more-send-item" @click="handleSendFile">
              <image class="img" :src="file"></image>
              <text>文件</text>
            </view>
          </template>
          <view v-if="showCloseService" class="more-send-item" @click="handleGoBack">
            <image class="img" :src="goBack"></image>
            <text>返回</text>
          </view>
          <view class="more-send-item" v-for="(item, index) in serviceCardList" :key="index"
            @click="handleClickService(item)">
            <image class="img" :src="httpToHttps(item.pic)"></image>
            <text>{{ item.name }}</text>
          </view>
        </view>
        <CommonTerms v-show="showCommonTerms" :loginStatus="loginStatus" @itemClick="setCommonTers"></CommonTerms>
      </view>
    </view>
    <u-select v-model="showCompanyPhone" mode="single-column" :list="companyPhoneList"
      @confirm="companyPhoneConfirm"></u-select>

      <ResumeDeliverDialog 
    ref="resumeDeliverDialog"  
    @deliverySuccess="hanldeDeliverySuccess"
    ></ResumeDeliverDialog>
  </page-wrap>
</template>

<script>
import TencentCloudChat from '@tencentcloud/chat';
import { faceTypeList, aimList } from "@/utils/data";
import {  formatTimeFlex, httpToHttps } from "@/utils/handle";
import {
  getUserInfo as getUserImInfo,
  getZpDetailAndApplyStatus,
  getZPChatInfo,
  sendJob,
  addChatZwRel,
  getCompanyPhoneList,
  doAgreePhoneEx,
  disAgreePhoneEx,
  applyPhoneEx,
  getResumeData,
  getMyIntendedTradeList,
  initUserInfo,
} from "@/api/index";
import { doCompanyPersonRightsConsume } from "@/api/modules/company";
import { sendSingleTextMessage, reportImLog, chatConversationCheck,
  getChatMsgList, chatReadLog, } from "@/api/modules/message.js";
import {
  chatDropInfo,
  checkServiceStat,
  subConsultOrder,
  getUserInfo,
  checkClick,
} from "@/api/modules/career";
import IMEventHandler from "@/utils/im";

import ResumeDeliverDialog from "@/components/ResumeDeliverDialog.vue";
import MyTextarea from "../components/MyTextarea.vue";
import CommonTerms from "../components/CommonTerms.vue";

export default {
  components: {
    ResumeDeliverDialog,
    MyTextarea,
    CommonTerms,
  },
  data() {
    return {
      defaultAvatar: this.$imgBase + "common/avatar_default.png",
      file: this.$imgBase + "career/chatService/file.png",
      img: this.$imgBase + "career/chatService/img.png",
      goBack: this.$imgBase + "career/chatService/back.png",
      personId: uni.getStorageSync("person-id").slice(2) || undefined,
      companyId: uni.getStorageSync("company-id"),
      loginStatus: uni.getStorageSync("login-status") || "person",
      chatId: "",
      conversationID: "",
      zpId: "",
      oppInfo: {
        name: "",
        avatar: "",
      },
      chatZwInfo: "",
      exchangeInfo: {}, // 电话交换信息
      exchangeStatusCode: "444",
      interviewStateList: {
        1: {
          textSelf: "您已发送面试邀请",
          textOpp: "对方发送了面试邀请",
        },
        2: {
          textSelf: "您接受了面试邀请",
          textOpp: "对方已接受面试邀请",
        },
        3: {
          textSelf: "您已拒绝面试邀请",
          textOpp: "对方拒绝了面试邀请",
        },
      },
      hasToudiIn7Days: "0", // 7天内是否已投递
      hasToudiIn3Days: "0", // 3天内是否已投递
      selfInfo: getApp().globalData.imInfo,
      chatList: [],
      isInit: true,
      msgEndTime: "",
      pageParam: {
        page: 0,
        pageSize: 20,
      },
      moreLoading: "loadmore",
      nextReqMessageID: "",
      isCompleted: '',
      loadText: {
        loadmore: "加载更多",
        loading: "加载中",
        nomore: "没有更多了",
      },
      curMsgTime: 0,
      tips: getApp().globalData.chatTips,
      sendText: "",
      scrollTo: 0,
      showPlaceholder: true,
      showClear: false,
      inputFocus: false,
      inputBottom: 0,

      moreSendVisible: false,
      faceList: [],
      faceVisible: false,
      sendMode: "text",
      toLast: "",
      jobData: "",
      companyPhoneList: [],
      invitationInfo: {}, // 邀请信息
      hasObserveTaskCourse: new Set(),
      lines: 0,
      cPhoneSelected: null,
      companyPhoneConfirmCallback: null,
      showCompanyPhone: false,
      companyImId: "",
      resumeData: null,
      resumeProps: {
        iname: "Iname_p",
        pic: "src_p",
        age: "Nianling_p",
        gznum: "Gznum_p",
        sex: "Sex_p",
        edus: "Edu_p",
        yuex: "yuex",
        work_des: "work_des",
        edu_des: "edu_des",
        grzz: "Grzz_p",
      },
      statusText: "",
      oppChatList: [],
      showCommonTerms: false,
      hasBeenSet: false,
      isAutoSendMsg: true, // 绑定职位是否自动发送消息
      isShowAction: true,
      showCloseService: false,
      showServiceEva: false,
      serviceCardList: [],
      longServiceCardList: [], // 存储起来，用于点击结束服务相关逻辑
      shortServiceCardList: [], // 存储起来，用于点击结束服务相关逻辑
      currentService: {},
      consultantInfo: {},
      personType: 0,
      isAdviser: false,
      adviser: getApp().globalData.adviser,
      showRole: false, // 是否显示顾问信息
      isReconnect: false,
      canClick: false,
      consultantType: 0,
      TencentCloudChat,
      chat: getApp().globalData.tim,
      httpToHttps,
    };
  },
  computed: {
    // 是否人企沟通
    isPersonAndCompany() {
      if (this.chatId.indexOf("_") > -1) {
        return true;
      }
      return false;
    },
  },
  watch: {
    inputFocus(val) {
      if (val) {
        this.sendMode = "text";
        this.showCommonTerms = false;
        this.moreSendVisible = false;
      }
    },
    sendMode(val) {
      if (val == "text") {
        this.faceVisible = false;
        this.moreSendVisible = false;
      } else {
        this.faceVisible = true;
        this.moreSendVisible = false;
      }
    },
  },
  onShow() {
    // 从服务管理页面跳转过来时候需要调用
    getApp().globalData.userIsConsultant && this.chatDropInfoFn();
  },
  onLoad(opt) {
    this.chatId = opt.chatId;
    if (opt.conversationID) {
      this.conversationID = opt.conversationID;
    } else {
      this.conversationID = 'C2C'+this.chatId;
    }
    // 如果当前的登陆人是顾问，就去请求卡片服务
    getApp().globalData.userIsConsultant && this.chatDropInfoFn();
    this.getUserInfoFn();
    this.zpId = opt.zpId;
    uni.getStorageSync("consultantId", this.chatId); // 用户端传过来的chatId就是consultantId
    if (opt.isAutoSendMsg == 0) {
      this.isAutoSendMsg = false;
    }
    // 简历工坊：24223415_cm1659576030119
    // 顾问管家：24371169
    if (
      (this.chatId == "24223415_cm1659576030119" ||
        this.chatId == "24371169") &&
      this.loginStatus == "person"
    ) {
      this.isShowAction = false;
    }

    this.isAdviser = opt.isAdviser;
    if (this.isAdviser) {
      this.isShowAction = false;
    }
  },
  created() {
    this.$bus.$on("RECEIVE_CHATING_MESSAGE", (messageList) => {
      // if (this.chatId == data.account) {
      //   this.handleChatInit();
      // }
      this.handleMessageList(messageList, true);
    });
    this.$bus.$on("LOGIN_SUCCESS", () => {
      uni.hideLoading();
      this.getChatOpp();
      this.handleChatInit();
    });
    // this.$bus.$on("MSG_RECEIPT_CHANGE", (data) => {
    //   if (data && !data.receipt_msgs) return;
    //   // 收到对方已读消息
    //   for (let i = 0; i < data.receipt_msgs.length; i++) {
    //     let unreadItem = data.receipt_msgs[i];
    //     let messageList = getApp().globalData.messageList || [];
    //     messageList.forEach((ele) => {
    //       if (ele.from_username == this.chatId) {
    //         if (!ele.receipt_msgs) ele.receipt_msgs = [];
    //         ele.receipt_msgs.push(unreadItem);
    //       }
    //     });
    //     for (let k = this.chatList.length - 1; k > -1; k--) {
    //       if (this.chatList[k].msg_id == unreadItem.msg_id) {
    //         this.chatList[k].unreadCount = 0;
    //         break;
    //       }
    //     }
    //   }
    //   this.$bus.$emit("NEED_UPDATE_CONVERSATION");
    // });
    // 收到对方已读消息
    this.$bus.$on("MESSAGE_READ_BY_PEER", (data) => {
      if (!data) return;
      for (let i = 0; i < data.length; i++) {
        let unreadItem = data[i];

        for (let k = this.chatList.length - 1; k > -1; k--) {
          if (this.chatList[k].ID == unreadItem.ID) {
            this.chatList[k] = unreadItem;
            break;
          }
        }
      }
      // this.$bus.$emit("NEED_UPDATE_CONVERSATION");
    });
    this.getFaceList();
  },
  beforeDestroy() {
    this.$bus.$off("RECEIVE_CHATING_MESSAGE");
    this.$bus.$off("LOGIN_SUCCESS");
    this.$bus.$off("MSG_RECEIPT_CHANGE");
    this.$bus.$off("MESSAGE_READ_BY_PEER");
    this.handleResetNum();
  },
  mounted() {
    this.companyImId = this.chatId;
    if (this.isAdviser) {
      this.setChatOpp();
    } else {
      this.getChatOpp();
    }
    this.getConversationId().then((res) => {
      this.handleChatInit();
    })
    this.resetSendMode();
    this.getZPChatInfo();
    this.getUserInfoFn();
    !this.isPersonAndCompany && this.checkClickFn();

    this.handleResetNum();
  },
  methods: {
    checkClickFn() {
      const params = {
        loginStatus: getApp().globalData.loginStatus,
        chatId: this.chatId,
      };
      checkClick(params).then((res) => {
        if (res.code == 200) {
          this.canClick = true;
        } else {
          this.canClick = false;
        }
      });
    },
    handleGoBack() {
      this.serviceCardList = this.longServiceCardList;
      this.showCloseService = false;
    },
    getUserInfoFn() {
      getUserInfo({ uid: "" }).then((res) => {
        if (res.code == 200) {
          if (res.data && res.data.personName) {
            // 0：普通用户 1：职途卡用户
            this.personType = 1;
          } else {
            this.personType = 0;
          }
        }
      });
    },
    subConsultOrderFn(service) {
      let params;
      if (service.serviceId == 1 || service.serviceId == 4) {
        params = {
          consultantId: this.chatId,
          personId: this.personId,
          serviceId: service.serviceId,
          serviceType: service.key,
          mallProductId: service.mallProductId,
          sourceType: 3,
          personType: this.personType,
        };
      }
      subConsultOrder(params).then((res) => {
        if (res.code == 200) {
          // 获取最新服务卡片的状态
          this.chatDropInfoFn();
        } else {
          uni.showToast({ icon: "", title: res.status_desc, duration: 2000 });
        }
      });
    },
    handleEndService(service) {
      this.sendEndServiceCard(service);
      setTimeout(() => {
        this.sendServiceEvaCard(service);
      }, 100);
    },
    handleEvaluate(service) {
      uni.navigateTo({
        url: `/pagesSub/userCenter/evaluateCard/index?serviceName=${service.name}&serviceRecordId=${service.serviceRecordId}&consultantName=${service.consultantName}`,
      });
    },
    sendServiceEvaCard(service) {
      var content = {
        send_uid: this.selfInfo.uname,
        receive_uid: this.chatId,
        content: service.name,
        share: {
          type: 106,
          isCardService: 1,
          service: {
            name: service.name,
            cancelText: "",
            confirmText: "立即评价",
            pic: service.pic,
            serviceId: service.serviceId,
            titleImg: service.titleImg,
            titleImg: service.titleImg,
            serviceRecordId: service.serviceRecordId,
            consultantName: service.consultantName,
          },
        },
        person_iname: this.selfInfo.nickname,
        person_pic: this.selfInfo.pic,
        is_send: "1",
        idate: new Date().getTime(),
      };
      this.createMsgContent(content);
    },
    sendEndServiceCard(service) {
      let content = {
        send_uid: this.selfInfo.uname,
        receive_uid: this.chatId,
        content: "",
        share: {
          type: 104,
          state: 1,
          tips: {
            textSelf: `您已经确认结束${service.name}服务`,
            textOpp: `对方已经确认结束${service.name}服务`,
          },
        },
        person_iname: this.selfInfo.nickname,
        person_pic: this.selfInfo.pic,
        is_send: "1",
        idate: new Date().getTime(),
      };
      this.createMsgContent(content);
    },
    serviceConfirm(service) {
      let content = {
        send_uid: this.selfInfo.uname,
        receive_uid: this.chatId,
        content: "",
        share: {
          type: 104,
          state: 1,
          tips: {
            textSelf: `您已经确认开启${service.name}服务`,
            textOpp: `对方已经确认开启${service.name}服务`,
          },
        },
        person_iname: this.selfInfo.nickname,
        person_pic: this.selfInfo.pic,
        is_send: "1",
        idate: new Date().getTime(),
      };
      this.createMsgContent(content);
      this.subConsultOrderFn(service);
    },
    serviceCancel(service) {
      let content = {
        send_uid: this.selfInfo.uname,
        receive_uid: this.chatId,
        content: "",
        share: {
          type: 104,
          state: 2,
          tips: {
            textSelf: `您已经放弃${service.name}服务`,
            textOpp: `对方已经放弃${service.name}服务`,
          },
        },
        person_iname: this.selfInfo.nickname,
        person_pic: this.selfInfo.pic,
        is_send: "1",
        idate: new Date().getTime(),
      };
      this.createMsgContent(content);
    },
    chatDropInfoFn() {
      const params = {
        consultantId: this.personId,
        personId: +this.chatId,
      };
      chatDropInfo(params).then((res) => {
        if (res.code == 200) {
          this.shortServiceCardList = res.data.serviceCard.slice(0, 4);
          this.longServiceCardList = res.data.serviceCard;
          this.consultantInfo = res.data.consultantInfo;
          this.consultantType = res.data.consultantType;
          res.data.serviceCard.forEach((item) => {
            item.consultantName = this.consultantInfo.iname;
            item.consultantPic = this.consultantInfo.pic;
          });
          this.serviceCardList = res.data.serviceCard;
        }
      });
    },
    handleClickAvatar(item) {
      // 如果企业端，都不能点击
      if (getApp().globalData.loginStatus == "company") return;

      // 如果是人才端
      if (getApp().globalData.loginStatus == "person") {
        // 1、对方是企业
        if (this.isPersonAndCompany) return; // 都不能点击
        // 2、对方是顾问或用户 暂时由后端接口判断是否可以点击
        if (!this.canClick) return; // canClick已经在mounted请求

        if (item.from == this.personId) {
          uni.navigateTo({
            url: `/pagesSub/career/consultant/userDetail/index?personId=${item.content.from_id}`,
          });
        } else {
          uni.navigateTo({
            url: `/pagesSub/career/consultant/consultantDetail/index?personId=${item.content.from_id}`,
          });
        }
      }

      // 如果已经切换到顾问端
      if (getApp().globalData.loginStatus == "consultant") {
        if (this.isPersonAndCompany) return; // 1、如果对方是企业，也不能点击
        // 而且当前登录人是职途顾问
        if (this.consultantType == 1) {
          if (item.from == this.personId) {
            uni.navigateTo({
              url: `/pagesSub/career/consultant/consultantDetail/index?personId=${item.content.from_id}`,
            });
          } else {
            uni.navigateTo({
              url: `/pagesSub/career/consultant/userDetail/index?personId=${item.content.from_id}`,
            });
          }
        } else {
          uni.navigateTo({
            url: `/pagesSub/career/consultant/userDetail/index?personId=${item.content.from_id}`,
          });
        }
      }
    },
    // handleClickAvatar2(item) {
    //   // 如果登陆人是企业端，都不能点击
    //   if (getApp().globalData.loginStatus == "company") return;
    //   // 人才端登录的情况
    //   if (getApp().globalData.loginStatus == "person") {
    //     // 1、对方是企业
    //     if (this.isPersonAndCompany) return; // 都不能点击
    //     // 2、对方是顾问或用户 暂时由后端接口判断是否可以点击
    //     if (!this.canClick) return; // canClick已经在mounted请求
    //   }
    //   // 先判断当前登陆人是顾问
    //   if (getApp().globalData.userIsConsultant) {
    //     if (this.isPersonAndCompany) return; // 1、如果对方是企业，也不能点击

    //     // 2、对方是顾问或用户 暂时由后端接口判断是否可以点击
    //     if (!this.canClick) return; // canClick已经在mounted请求
    //     if (item.content.from_id == this.personId) {
    //       uni.navigateTo({
    //         url: `/pagesSub/career/consultant/consultantDetail/index?personId=${item.content.from_id}`,
    //       });
    //     } else {
    //       uni.navigateTo({
    //         url: `/pagesSub/career/consultant/userDetail/index?personId=${item.content.from_id}`,
    //       });
    //     }
    //   } else {
    //     // 3、对方是顾问或用户 暂时由后端接口判断是否可以点击
    //     if (!this.canClick) return; // canClick已经在mounted请求
    //     if (item.content.from_id == this.personId) {
    //       uni.navigateTo({
    //         url: `/pagesSub/career/consultant/userDetail/index?personId=${item.content.from_id}`,
    //       });
    //     } else {
    //       uni.navigateTo({
    //         url: `/pagesSub/career/consultant/consultantDetail/index?personId=${item.content.from_id}`,
    //       });
    //     }
    //   }
    // },
    handleClickService(service) {
      console.log("handleClickService", service);

      this.currentService = service;
      if (service.serviceId == 2 || service.serviceId == 3) {
        uni.showModal({
          title: "",
          content: `${service.name}服务暂未开放，敬请期待`,
        });
        return;
      }
      if (
        service.isOpen == 0 &&
        service.name != "结束服务" &&
        !this.showCloseService
      ) {
        uni.showModal({
          title: "提示",
          content: "请先去开启该项服务后再发送服务卡片",
          success: (res) => {
            if (res.confirm) {
              uni.navigateTo({
                url: "/pagesSub/userCenter/serviceManage/index",
              });
              this.moreSendVisible = false;
            }
          },
        });
        return;
      }
      if (service.name === "结束服务") {
        this.serviceCardList = this.shortServiceCardList;
        this.showCloseService = true;
        return;
      }
      if (service.name === "服务评价") {
        this.serviceCardList = this.shortServiceCardList;
        this.showCloseService = true;
        this.showServiceEva = true;
        return;
      }
      if (this.showCloseService && service.type == 101) {
        const params = {
          consultantId: this.personId,
          serviceId: service.serviceId,
          personId: this.chatId, // chatId 就是用户的 personId
          type: 2, // 发送卡片检查
        };
        checkServiceStat(params).then((res) => {
          if (res.code == 200) {
            var content = {
              send_uid: this.selfInfo.uname,
              receive_uid: this.chatId,
              content: service.name,
              share: {
                type: 105,
                isCardService: 1,
                service: {
                  name: service.name,
                  cancelText: "",
                  confirmText: "确认结束",
                  pic: service.pic,
                  serviceId: service.serviceId,
                  titleImg: service.titleImg,
                  serviceRecordId: res.data,
                  consultantName: service.consultantName || "",
                  consultantPic: service.consultantPic || "",
                },
              },
              person_iname: this.selfInfo.nickname,
              person_pic: this.selfInfo.pic,
              is_send: "1",
              idate: new Date().getTime(),
            };
            this.createMsgContent(content);
            this.moreSendVisible = false;
            this.showCloseService = false;
          } else {
            uni.showToast({
              icon: "",
              title: res.status_desc,
              duration: 1000,
            });
          }
        });
        return;
      }
      if (service.type == 101) {
        const params = {
          consultantId: this.personId,
          serviceId: service.serviceId,
          personId: this.chatId, // chatId 就是用户的 personId
          type: 1, // 发送卡片检查
        };
        checkServiceStat(params).then((res) => {
          if (res.code == 200) {
            uni.showModal({
              title: service.title,
              content: service.tip,
              success: (res) => {
                if (res.confirm) {
                  var content = {
                    send_uid: this.selfInfo.uname,
                    receive_uid: this.chatId,
                    content: service.name,
                    share: {
                      type: service.type,
                      isCardService: 1,
                      service: service,
                    },
                    person_iname: this.selfInfo.nickname,
                    person_pic: this.selfInfo.pic,
                    is_send: "1",
                    idate: new Date().getTime(),
                  };
                  this.createMsgContent(content);
                  this.moreSendVisible = false;
                }
              },
            });
          } else {
            uni.showModal({
              title: "",
              content: res.status_desc,
            });
          }
        });
      } else {
        var content = {
          send_uid: this.selfInfo.uname,
          receive_uid: this.chatId,
          content: service.name,
          share: {
            type: service.type,
            isCardService: 1,
            service: service,
          },
          person_iname: this.selfInfo.nickname,
          person_pic: this.selfInfo.pic,
          is_send: "1",
          idate: new Date().getTime(),
        };
        this.createMsgContent(content);
        this.moreSendVisible = false;
      }
    },
    getChatOpp() {
      let that = this;
      // 如果当前登陆人是顾问，就用自己的personId去请求信息，如果是用户，就用chatId请求
      // 但如果是本身登陆人对顾问，在职途卡绑定了顾问账号，就会出现聊天页面顶部title和头像都是自己的问题
      let param = {
        uname: this.chatId,
      };
      getUserImInfo(param).then((res) => {
        if (res.code == 200) {
          this.oppInfo.name = res.data.nickname;
          this.oppInfo.avatar = this.httpToHttps(res.data.pic);
          uni.setNavigationBarTitle({
            title: that.oppInfo.name,
          });
        }
      });
    },
    setChatOpp() {
      this.oppInfo.name = this.adviser.nickName;
      this.oppInfo.avatar = this.adviser.avatar;
    },
    // 获取招聘聊天信息
    getZPChatInfo() {
      let params = {
        person_id: this.personId, // 人才id
        company_im_id: this.companyImId,
        from_who: this.loginStatus,
      };
      getZPChatInfo(params).then((res) => {
        // console.log(res.info)
        if (res && res.info) {
          this.exchangeInfo = res.info.exchange_info;
          this.exchangeStatusCode = res.info.exchange_status_code;
          this.hasToudiIn7Days = res.info.has_toudi_in_7days;
          this.invitationInfo = res.info.invitation_info;
          this.chatZwInfo = res.info.chat_zw_info;
          this.chatZwInfo && this.getJobDetail(this.chatZwInfo.zw_id);
          if (this.zpId) {
            if (!this.chatZwInfo || this.chatZwInfo.zw_id != this.zpId) {
              // this.handleSendPosition();
              this.addChatZwRel();
              this.getJobDetail(this.zpId);
            }
          }
        }
      });
    },
    // 坊小二初始状态下，会有一条固定的系统消息
    setSystemMsg(msg) {
      if (this.chatList.length < 1) {
        this.chatList.push({
          type: 'TIMTextElem',
          to: this.selfInfo.uname,
          avatar: "",
          flow: "in",
          from: this.chatId,
          isRead: true,
          isPeerRead: true,
          payload: {
            text: msg,
          },
          ctime_ms: new Date().getTime(),
          timeParse: formatTimeFlex(new Date(), 1),
          showTime: true,
        });
      }
    },
    handleMessageList(messageList, isReceipt) {
      this.oppChatList = [];
      let messageListTemp = messageList.map((item) => {
        item.showTime = this.handleShowTime(item.time*1000);
        if (item.flow == 'in' && !item.isPeerRead) {
          this.oppChatList.push(item);
        }
        return {
          ...item,
          ctime_ms: item.time*1000,
          timeParse: formatTimeFlex(item.time*1000, 1),
        };
      });
      if (isReceipt) {
        this.chatList.push(...messageListTemp);
      } else {
        this.chatList = messageListTemp.concat(this.chatList);
      }

      if (isReceipt) {
        this.toBottom();
      }
      this.handleResetNum();
      // this.handleReceiptReport();
    },
    snakeToCamel(str) {
      // // 将底杠后的字母转换为大写，并移除底杠
      // const camelCaseStr = str.replace(/_([a-z])/g, (match, letter) => letter.toUpperCase());
      // 将第一个字母转换为小写
      if (str.toLowerCase() === 'url') {
        return 'url';
      }
      return str.charAt(0).toLowerCase() + str.slice(1);
    },
    convertKeysToCamelCase(obj) {
      if (Array.isArray(obj)) {
        return obj.map(item => this.convertKeysToCamelCase(item));
      } else if (typeof obj === 'object' && obj !== null) {
        const newObj = {};
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            const newKey = this.snakeToCamel(key);
            newObj[newKey] = this.convertKeysToCamelCase(obj[key]);
          }
        }
        return newObj;
      }
      return obj;
    },
    formatMsgList(msgList) {
      msgList = msgList.reverse();
      return msgList.map((item) => {
        let time = item.msgTime.replace(/-/g, '/');
        time = Math.floor(new Date(time).getTime() / 1000);
        item.time = time;

        item.type = item.msgBody[0].msgType;
        item.to = item.targetAccount;
        item.avatar = "";
        item.flow = this.selfInfo.uname === item.fromAccount? "out" : "in";
        item.from = item.fromAccount;
        item.isRead = item.isRead;
        item.isPeerRead = item.isPeerRead;
        try {
          let msgContent = item.msgBody[0].msgContent && JSON.parse(item.msgBody[0].msgContent);
          item.payload = this.convertKeysToCamelCase(msgContent);
        } catch (error) {
          console.error(error);
          item.payload = {};
        }
        return item;
      });
    },
    getChatList(toBtm) {
      if (this.isCompleted || !this.conversationID) {
        return
      }
      this.moreLoading = "loading";

      const params = {
        fromAccount: this.selfInfo.uname,
        targetAccount: this.chatId,
        endTime: this.msgEndTime,
        pageSize: 20,
        conversationId: this.conversationId,
      }
      getChatMsgList(params).then(res => {
        this.moreLoading = "loadmore";
        if (res.data && res.data.length) {
          let messageList = this.formatMsgList(res.data);
          this.handleMessageList(messageList);
          this.msgEndTime = messageList[0].msgTime;
        }

        // 坊小二，简历工坊职位id："53522147"
        if (!res.data && this.chatId == "24223415_cm1659576030119") {
          this.setSystemMsg("您好，欢迎来到简历工坊，我是坊小二，客官有什么需要？");
        }

        // 职业顾问管家
        if (!res.data && this.chatId == "24371169") {
          this.setSystemMsg(
            "您好，我们已收到消息，导师将会在24小时内与您联系，敬请期待"
          );
        }

        let haveMore = !res.data || !res.data.length;
        if (haveMore) {
          this.moreLoading = "nomore";
          return false;
        }

        if (toBtm) {
          this.toBottom();
        }
      })

      return

      let that = this;
      let chat = getApp().globalData.tim;
      
      // 打开某个会话时，第一次拉取消息列表，注意！第一次拉取时不要传入 nextReqMessageID
      const options = {
        conversationID: this.conversationID,
      }
      if (this.nextReqMessageID) {
        options.nextReqMessageID = this.nextReqMessageID;
      }
      let promise = chat.getMessageList(options);
      promise.then(function(imResponse) {
        that.moreLoading = "loadmore";
        
        console.log("getMessageList", imResponse);
        const messageList = imResponse.data.messageList; // 消息列表。
        that.nextReqMessageID = imResponse.data.nextReqMessageID; // 用于续拉，分页续拉时需传入该字段。
        that.isCompleted = imResponse.data.isCompleted; // 表示是否已经拉完所有消息。isCompleted 为 true 时，nextReqMessageID 为 ""。

        that.handleMessageList(messageList);

        if (that.isCompleted) {
          that.moreLoading = "nomore";
          return false;
        }

        if (toBtm) {
          that.toBottom();
        }
      });
    },
    handleChatInit() {
      this.oppChatList = [];
      // let chatList = getApp().globalData.messageList.filter(
      //   (ele) => ele.from_username == this.chatId
      // );
      // if (chatList.length) {
      //   this.msgEndTime = formatTime(
      //     +chatList[0].msgs[0].ctime_ms - 500,
      //     "yyyy-MM-dd HH:mm:ss"
      //   );
      //   let receiptMsgs = chatList[0].receipt_msgs || [];
      //   chatList = chatList[0].msgs.map((ele) => {
      //     ele.contentParse = {
      //       type: 0,
      //       share: {},
      //     };
      //     if (ele.content.msg_body.text) {
      //       try {
      //         ele.contentParse = JSON.parse(ele.content.msg_body.text);
      //       } catch (e) {
      //         ele.contentParse = {
      //           type: 1,
      //           content: ele.content.msg_body.text,
      //         };
      //       }
      //     }
      //     for (let i = 0; i < receiptMsgs.length; i++) {
      //       if (ele.msg_id == receiptMsgs[i].msg_id) {
      //         ele.unreadCount = receiptMsgs[i].unread_count;
      //         break;
      //       }
      //     }
      //     if (/^\d+$/.test(ele.contentParse.idate)) {
      //       ele.contentParse.idate = +ele.contentParse.idate;
      //     }
      //     ele.idateStr = formatTime(ele.contentParse.idate, "MM-dd HH:mm");
      //     ele.timeParse = formatTimeFlex(ele.ctime_ms, 1);
      //     ele.showTime = this.handleShowTime(+ele.ctime_ms);

      //     if (this.chatId === ele.content.from_id) {
      //       this.oppChatList.push(ele);
      //     }

      //     return ele;
      //   });
      // }
      // this.chatList = chatList;

      // let lastItem = chatList[chatList.length - 1];
      // if (
      //   lastItem &&
      //   lastItem.contentParse.share &&
      //   lastItem.contentParse.share.type == 60
      // ) {
      //   this.getZPChatInfo();
      // }
      // this.handleReceiptReport();
      //初次加载自动拉取一次历史记录
      if (this.isInit && this.chatList.length < 1) {
        this.handleMore(true);
        this.isInit = false;
      }
      if (this.toLast != `item${this.chatList.length}`) {
        this.toBottom();
      }

      setTimeout(() => {
        if (this.isAdviser && this.chatList.length < 1) {
          this.sendDefaultAdviserMsg();
        }
      }, 1000);
    },
    // 重置会话未读数 
    handleResetNum() {
      if (!this.conversationID) return;
      let chat = getApp().globalData.tim;
     // 将某会话下所有未读消息已读上报,
    //  该接口是针对整个会话进行已读上报，调用成功后，会话的未读数（unreadCount）会被置为 0。
      let promise = chat.setMessageRead({conversationID: this.conversationID});
      promise.then(function(imResponse) {
        // 已读上报成功，指定 ID 的会话的 unreadCount 属性值被置为0
        console.log('setMessageRead success:', imResponse);
      }).catch(function(imError) {
        // 已读上报失败
        console.warn('setMessageRead error:', imError);
      });
      // this.$bus.$emit("NEED_UPDATE_CONVERSATION");

      const params = {
        fromAccount: this.selfInfo.uname,
        targetAccount: this.chatId,
      };
      chatReadLog(params)
    },
    handleMore(toBtm) {
      let isToBottom = false;
      if (typeof toBtm == "boolean") {
        isToBottom = true;
      }
      this.$set(this.pageParam, "page", this.pageParam.page + 1);
      this.getChatList(isToBottom);
    },
    handleShowTime(time) {
      let timeDiff = time - this.curMsgTime;
      if (timeDiff >= 5 * 60 * 1000 || timeDiff <= 0) {
        this.curMsgTime = time;
      }
      return timeDiff >= 5 * 60 * 1000 || timeDiff <= 0;
    },
    //创建消息体并发送
    createMsgContent(message) {
      console.log("createMsgContent", message);
      let chat = getApp().globalData.tim;
      const that = this;
      var isIMLogin = chat && chat.getLoginUser();
      if (!isIMLogin) {
        if (this.isReconnect) return;
        this.isReconnect = true;
        new IMEventHandler(() => {
          uni.hideLoading();
          that.isReconnect = false;
          that.createMsgContent(message);
        });
        return uni.showLoading({
          title: "正在连接",
          mask: true,
        });
      }
      if (!message) {
        return uni.showToast({
          icon: "none",
          title: "发送内容不能为空",
          duration: 1000,
        });
      }

      // 2. 发送消息
      let promise = chat.sendMessage(message);
      promise.then(function(imResponse) {
        // 发送成功
        console.log(imResponse);
        that.handleSendMsgSuccess(imResponse.data.message);
      }).catch(function(imError) {
        // 发送失败
        console.warn('sendMessage error:', imError);
        switch (imError.code) {
            case 20007:
              uni.showToast({
                title: "发送消息失败，已被对方拉入黑名单!",
                icon: "none",
                duration: 1000,
              });
              break;
            case 20003:
              that.register(that.chatId, message);
              break;
            default:
              uni.showToast({
                icon: "none",
                title: "消息发送失败",
                duration: 1000,
              });
              that.reportImLog({
                imError,
                params: message,
                selfinfo: that.selfInfo,
                source: "mp",
              });
              break;
          }
      });

    },
    // 发送文本消息
    handleSendMsg() {
      this.sendSingleTextMsg(this.sendText);
      // this.sendText = ''
    },
    // 发送单聊文本消息
    sendSingleTextMsg(text) {
      let chat = getApp().globalData.tim;

      let msg = {
        to: this.chatId , // 消息接收方的 userID 或 groupID
        conversationType: TencentCloudChat.TYPES.CONV_C2C,
        payload: {
          text: text,
        },
        // 如果您发消息需要已读回执，需购买旗舰版套餐，并且创建消息时将 needReadReceipt 设置为 true
        needReadReceipt: true,
      };
      let message = chat.createTextMessage(msg);
      this.createMsgContent(message);
    },
    // 成功发送消息处理
    handleSendMsgSuccess(message) {
      this.conversationID = message.conversationID;
      this.sendText = "";
      this.handleLinechange({ lineCount: 0 });
      this.chatList.push({
        ...message,
        timeParse: formatTimeFlex(message.time*1000, 1),
        showTime: this.handleShowTime(+message.time*1000),
      });
      this.toBottom();
    },
    // 是否请求电话弹框
    handleGetMobileClick() {
      if (this.exchangeStatusCode == 444) {
        uni.showModal({
          title: "温馨提醒",
          content: "是否想和对方交换手机号码？",
          success: (res) => {
            if (res.confirm) {
              this.handleApplyPhoneEx();
            }
          },
        });
      } else if (this.exchangeStatusCode == 200) {
        let phoneNumber = this.exchangeInfo.company_phone;
        this.handleCall(phoneNumber);
      }
    },
    // 确定请求电话
    handleApplyPhoneEx() {
        this.applyPhoneEx();
    },
    // 发送请求电话信息
    applyPhoneEx() {
      let params = {
        person_id: this.personId, // 人才id
        company_im_id: this.companyImId,
        from_who: this.loginStatus,
      };
      let conditionArr = {
        login_person_id: this.personId,
      };
      // 企业需要选择号码
      if (params.from_who == "company") {
        if (!this.cPhoneSelected) {
          this.showCompanyPhone = true;
          return;
        }
        conditionArr.company_phone = this.cPhoneSelected;
      }
      params.conditionArr = JSON.stringify(conditionArr);
      applyPhoneEx(params).then((res) => {
        if (res && res.code == 200) {
          this.handleGetMobile(1);
        } else {
          uni.showToast({
            title: res.status_desc,
            icon: "none",
          });
        }
      });
    },
    // 点击交换电话
    handleDoAgree() {
        this.doAgree();
    },
    // 同意交换
    doAgree() {
      if (this.exchangeStatusCode == 200) {
        return uni.showToast({
          icon: "none",
          title: "已完成交换",
        });
      }
      if (this.exchangeStatusCode != 750) return;

      let params = {
        person_id: this.personId, // 人才id
        company_im_id: this.companyImId,
        from_who: this.loginStatus,
      };
      // 企业需要选择号码
      if (params.from_who == "company") {
        if (!this.cPhoneSelected) {
          this.showCompanyPhone = true;
          return;
        }
        params.conditionArr = JSON.stringify({
          company_phone: this.cPhoneSelected,
        });
      }
      doAgreePhoneEx(params).then((res) => {
        if (res && res.code == 200) {
          this.handleGetMobile(2, res.info);
        } else {
          uni.showToast({
            icon: "none",
            title: res.status_desc,
            duration: 1000,
          });
        }
      });
    },
    // 拒绝交换
    doRefuse() {
      if (this.exchangeStatusCode == 200) {
        return uni.showToast({
          icon: "none",
          title: "已完成交换",
        });
      }
      if (this.exchangeStatusCode != 750) return;

      let params = {
        person_id: this.personId, // 人才id
        company_im_id: this.companyImId,
        from_who: this.loginStatus,
      };
      disAgreePhoneEx(params).then((res) => {
        if (res && res.code == 200) {
          this.handleGetMobile(3);
        } else {
          uni.showToast({
            icon: "none",
            title: res.status_desc,
            duration: 1000,
          });
        }
      });
    },

    // 极光发送交换电话消息
    handleGetMobile(status, info) {
      if (this.exchangeStatusCode == 200) {
        return uni.showToast({
          icon: "none",
          title: "已完成交换",
        });
      }
      let receive_mobile = "",
        receive_uname = "",
        send_mobile = "",
        send_uname = "";
      if (status == 2) {
          receive_mobile = info.company_phone;
          receive_uname = info.company_pname;
          send_mobile = info.puser_phone;
          send_uname = info.puser_name;
      }
      let contentText = "[交换电话]";
      const slave = {
        mobile_exchange_state: status,
        receive_mobile: receive_mobile,
        receive_uname: receive_uname,
        send_mobile: send_mobile,
        send_uid: this.selfInfo.uname,
        receive_uid: this.chatId,
        send_uname: send_uname || this.selfInfo.nickname,
        content: contentText,
      };

      var content = {
        share: {
          type: "60",
          slave: slave,
        },
        content: "交换电话",
        send_uid: this.selfInfo.uname,
        receive_uid: this.chatId,
        person_iname: this.selfInfo.nickname,
        person_pic: this.selfInfo.pic,
        is_send: "1",
        idate: new Date().getTime(),
        type: "60",
      };
      this.createMsgContent(content);
      this.getZPChatInfo();
    },

    // 选择图片
    handleSendPic() {
      uni.chooseMedia({
        count: 1,
        mediaType: ['image'], // 图片
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album'], // 从相册选择
        success: (res) => {
          this.sendPic(res);
          // var tempFilePaths = res.tempFilePaths[0]; //获取成功，读取文件路径

          // uni.uploadFile({
          //   url: uploadAction,
          //   filePath: tempFilePaths,
          //   name: "file",
          //   success: (fileRes) => {
          //     if (fileRes.data) {
          //       let imgPath = "https://img106.job1001.com/" + fileRes.data;
          //       imgPath = imgPath + "#" + imgPath; // App特殊格式
          //       this.sendPic(imgPath);
          //     }
          //   },
          //   fail: (err) => {
          //     uni.showToast({
          //       icon: "none",
          //       title: "图片发送失败",
          //     });
          //   },
          // });
        },
      });
    },
    // 发送图片
    sendPic(res) {
      // let content = {
      //   send_uid: this.selfInfo.uname,
      //   receive_uid: this.chatId,
      //   content: "图片",
      //   share: {
      //     type: 4,
      //     slave: {
      //       path: imgSrc,
      //     },
      //   },
      //   person_iname: this.selfInfo.nickname,
      //   person_pic: this.selfInfo.pic,
      //   is_send: "1",
      //   idate: new Date().getTime(),
      // };
      // this.createMsgContent(content);
      let message = this.chat.createImageMessage({
        to: this.chatId,
        conversationType: TencentCloudChat.TYPES.CONV_C2C,
        payload: { file: res },
        onProgress: function(event) { console.log('file uploading:', event) }
      });

      this.createMsgContent(message);
      this.moreSendVisible = false;
    },
    // 获取职位信息
    getJobDetail(id) {
      let params = {
        zp_id: id || this.zpId || (this.chatZwInfo && this.chatZwInfo.zw_id),
        person_id: this.personId,
        Prnd: getApp().globalData.userInfo && getApp().globalData.userInfo.Prnd,
      };
      getZpDetailAndApplyStatus(params).then((res) => {
        let jobdata = res.data || res;
        if (jobdata.gznum1 == 0 && jobdata.gznum2 == 0) {
          jobdata.gznum = "经验不限";
        } else if (jobdata.gznum1 == 0 && jobdata.gznum2 > 0) {
          jobdata.gznum = jobdata.gznum1 + "年以下";
        } else if (jobdata.gznum1 > 0 && jobdata.gznum2 == 0) {
          jobdata.gznum = jobdata.gznum1 + "年以上";
        } else if (jobdata.gznum1 > 0 && jobdata.gznum2 > 0) {
          jobdata.gznum = jobdata.gznum1 + "-" + jobdata.gznum2 + "年";
        }
        if ((jobdata.ComTrade || []).length > 15) {
          jobdata.ComTrade = jobdata.ComTrade.substr(0, 15) + "...";
        }

        if (!jobdata.edus) {
          jobdata.edus = "学历不限";
        }
        this.jobData = jobdata;
      });
    },
    // 关联职位
    addChatZwRel() {
      let params = {
        person_id: this.personId, // 人才id
        company_im_id: this.companyImId,
        zw_id: this.zpId,
        from_who: this.loginStatus,
        conditionArr: "",
      };
      addChatZwRel(params).then((res) => {
        this.getZPChatInfo();
        if (this.isAutoSendMsg) {
          this.sendSingleTextMsg(
            "您好，我对贵公司很感兴趣，希望可以有机会聊聊。"
          );
        }
      });
    },
    // 发送职位
    handleSendPosition() {
      this.addChatZwRel();

      let jobParams = {
        zw_id: this.zpId,
      };
      getZpDetailAndApplyStatus(jobParams).then((res) => {
        let jobdata = res.data || res;
        if (jobdata.gznum1 == 0 && jobdata.gznum2 == 0) {
          jobdata.gznum = "经验不限";
        } else if (jobdata.gznum1 == 0 && jobdata.gznum2 > 0) {
          jobdata.gznum = jobdata.gznum1 + "年以下";
        } else if (jobdata.gznum1 > 0 && jobdata.gznum2 == 0) {
          jobdata.gznum = jobdata.gznum1 + "年以上";
        } else if (jobdata.gznum1 > 0 && jobdata.gznum2 > 0) {
          jobdata.gznum = jobdata.gznum1 + "-" + jobdata.gznum2 + "年";
        }
        if ((jobdata.ComTrade || []).length > 15) {
          jobdata.ComTrade = jobdata.ComTrade.substr(0, 15) + "...";
        }

        if (!jobdata.edus) {
          jobdata.edus = "学历不限";
        }
        this.jobData = jobdata;

        var content = {
          send_uid: this.selfInfo.uname,
          receive_uid: this.chatId,
          content: "职位",
          share: {
            type: 20,
            slave: {
              firstSend: "1",
              position_change: "1",
              position_company: jobdata.cname,
              position_company_id: jobdata.uid,
              position_edus: jobdata.edus,
              position_gznum: jobdata.gznum,
              position_id: jobdata.id,
              position_logo: "",
              position_name: jobdata.jtzw,
              position_regionname: jobdata.regionid_name,
              position_salary: jobdata.xzdy,
              sa_person_id: "",
            },
          },
          person_iname: this.selfInfo.nickname,
          person_pic: this.selfInfo.pic,
          is_send: "1",
          idate: new Date().getTime(),
        };
        this.createMsgContent(content);
      });
    },

    // 表情包插入输入框
    strToEmoji(title) {
      this.sendText += title;
    },
    // 表情数组
    getFaceList() {
      let face = faceTypeList;
      face.forEach((item, index) => {
        this.faceList.push({
          title: item,
          src: `https://j.job1001.com/yl1001plugin/YL1001Editor/kindeditor-4.1.10/plugins/emoticons/images/${index}.gif`,
        });
      });
    },
    changeToEmoji(cont) {
      var that = this;
      var reg = /\[.+?\]/g;
      let str;
      str = cont.replace(reg, function (a) {
        let index = that.faceList.findIndex((ele) => ele.title == a);
        if (index > -1) {
          return (
            '<img class="emoji" style="vertical-align: -6px;" src="' +
            that.faceList[index].src +
            '"/>'
          );
        } else {
          return a;
        }
      });
      return str;
    },
    // 图片预览
    handlePreviewImage(src) {
      uni.previewImage({
        current: "", // 当前显示图片的 http 链接
        urls: [src], // 需要预览的图片 http 链接列表
      });
    },
    resetSendMode() {
      this.sendMode = "text";
    },
    // +更多发送类型
    handleMoreSendClick() {
      this.faceVisible = false;
      this.showCommonTerms = false;
      this.moreSendVisible = !this.moreSendVisible;
    },
    // 发送模式：表情/文本
    handleSendModeClick() {
      this.moreSendVisible = false;
      this.showCommonTerms = false;
      this.faceVisible = !this.faceVisible;
      if (this.faceVisible) {
        this.inputFocus = false;
        this.sendMode = "emoji";
      } else {
        this.inputFocus = true;
        this.sendMode = "text";
      }
      this.toBottom();
    },
    // 滚动到底部
    toBottom() {
      let flag = this.chatList.length;
      this.toLast = "item";
      setTimeout(() => {
        this.$nextTick(() => {
          this.toLast = "item" + flag;
        });
      }, 500);
    },
    // 拨打电话
    handleCall(mobile) {
      if (!mobile) return;
      uni.makePhoneCall({
        phoneNumber: mobile,
      });
    },
    // 投递简历
    handleDeliver() {
      if (this.chatZwInfo && this.chatZwInfo.zw_id) {
       // this.applyto();
        this.verifyResumeDelivery();
      } else {
        return uni.showModal({
          title: "温馨提示",
          content: "请先选择职位,再投递简历",
          success: (res) => {
            if (res.confirm) {
              uni.navigateTo({
                url: "/pagesSub/public/jobList/index?chatId=" + this.chatId,
              });
            }
          },
        });
      }
    },

    
    hanldeDeliverySuccess(){
      this.hasToudiIn7Days = 1;
      this.getZPChatInfo();
    },
     // 投递简历校验
     verifyResumeDelivery(){ 
      this.$refs.resumeDeliverDialog.verifyResumeDelivery({
        companyId: this.jobData.uid,
        positionId: this.jobData.id,
        jobName: this.jobData.jtzw,
        personId: this.personId,
      } );  
    }, 

    //投递职位
    applyto: function () {
      var data = {
        title: "",
        content: "贵公司，您好，我基本符合以上职位的条件，应聘该职，谢谢",
        company: this.jobData.uid,
        position: this.jobData.id,
        job: this.jobData.jtzw,
        user: this.personId,
        wage: "0",
      };
      sendJob(data).then((res) => {
        var _data = res;
        if (_data.status == "OK") {
          this.hasToudiIn7Days = 1;
          uni.showToast({
            icon: "none",
            title: "投递成功",
          });
          this.getZPChatInfo();
        } else if (_data.code == "1") {
          uni.showModal({
            title: "提示",
            content: "您的简历未完善，填写完善后即可投递简历",
            success: function (modalRes) {
              if (modalRes.confirm) {
                uni.navigateTo({
                  url: "/pagesSub/newResume/index",
                });
              }
            },
          });
        } else {
          let errorMsg = "";
          switch (_data.code) {
            case "2": // 2:三天内对同一职位进行投递     － －正常投递
              errorMsg = "三天内不能对同一职位进行重复投递！";
              break;
            case "10": // 10:人才已针对此公司保密      － －正常投递
              errorMsg = "您已对该公司进行屏蔽，请确认！";
              break;
            case "502":
              errorMsg = "您今日的投递次数已用完，请明天再投！";
              break;
          }
          uni.showToast({
            title: errorMsg,
            icon: "none",
            duration: 1000,
          });
        }
      });
    },

    // 查看面试
    handleInterViewClick() {
      uni.navigateTo({
        url:
          "/pagesSub/userCenter/interview/index?id=" +
          this.invitationInfo.pmail_id,
      });
    },

    // 单条或多条消息的已读通知
    handleReceiptReport() {
      let chat = getApp().globalData.tim;
      console.log('oppChatList', this.oppChatList)
      if (!this.oppChatList.length) return;
      chat && chat.sendMessageReadReceipt(this.oppChatList).then(function() {});
    },

    // 企业发送请求电话信息
    getCompanyPhoneList(callback) {
      let params = {
        company_id: this.companyId,
        person_login_id: this.personId,
      };
      getCompanyPhoneList(params).then((res) => {
        this.companyPhoneList = [];
        if (res.code == 200) {
          res.info.hr_shouji &&
            this.companyPhoneList.push({
              label: res.info.hr_shouji,
              value: res.info.hr_shouji,
            });
          res.info.company_phone &&
            this.companyPhoneList.push({
              label: res.info.company_phone,
              value: res.info.company_phone,
            });
          if (this.companyPhoneList.length) {
            if (this.companyPhoneList.length > 1) {
              this.showCompanyPhone = true;
              this.companyPhoneConfirmCallback = callback;
            } else {
              this.cPhoneSelected = this.companyPhoneList[0].value;
              callback && callback();
            }
          } else {
            uni.showToast({
              title: "请先绑定手机号码",
              icon: "none",
              duration: 1000,
            });
          }
        } else {
          uni.showToast({
            title: res.status_desc,
            icon: "none",
            duration: 1000,
          });
        }
      });
    },

    handleLinechange(detail) {
      if (detail.lineCount > 2) {
        this.lines = "lines2";
      } else if (detail.lineCount > 1) {
        this.lines = "lines1";
      } else {
        this.lines = "0";
      }
    },

    handleBoardChange(height) {
      this.inputBottom = height;
      this.toBottom();
    },
    // 查看简历
    handleResumeClick(item) {
      let personId = this.chatId;
      if (item && item.person_id) {
        personId = item.person_id;
      }
      uni.navigateTo({
        url: "/pagesSub/resume/resumeDetail/index?personId=" + personId,
      });
    },
    // 企业确定号码
    companyPhoneConfirm(e) {
      this.cPhoneSelected = e[0].value;
      this.companyPhoneConfirmCallback && this.companyPhoneConfirmCallback();
    },
    // 获取个人简历信息
    getPersonResumeData() {
      this.getMyIntendedTradeList();
      let params = {
        person_id: this.chatId,
      };
      getResumeData(params).then((res) => {
        if (res.code == 200) {
          this.resumeData = res.data;
          if (res.data.personWorkArr && res.data.personWorkArr.length) {
            this.resumeData.work_des =
              res.data.personWorkArr[0].company +
              "·" +
              res.data.personWorkArr[0].jtzw;
          }
          if (res.data.personEdusArr && res.data.personEdusArr.length) {
            this.resumeData.edu_des =
              res.data.personEdusArr[0].school +
              "·" +
              res.data.personEdusArr[0].zym;
          }
        }
      });
    },
    // 求职意向（获取person_status）
    getMyIntendedTradeList() {
      let params = {
        personId: this.chatId,
      };
      getMyIntendedTradeList(params).then((res) => {
        if (res.code == 200) {
          let status = +res.data.personInfo.person_status;
          let item = aimList.find((ele) => +ele.value === +status);
          this.statusText = item ? item.label : "";
        }
      });
    },

    // 权益消耗
    rightsConsume(checkType) {
      const params = {
        personId: this.personId,
        companyId: this.companyId,
        checkType: checkType,
      };
      return doCompanyPersonRightsConsume(params);
    },

    // 注册IM
    register(personId, message) {
      let param = {
        uname: personId,
      };
      initUserInfo(param).then((res) => {
        if (res && +res.code === 200) {
          this.handleSendMsg(message);
        }
      });
    },
    handleShowCommonTerms() {
      this.showCommonTerms = !this.showCommonTerms;
      this.inputFocus = false;
      this.faceVisible = false;
      this.moreSendVisible = false;
      this.sendMode = "text";
    },
    // 选中常用语
    setCommonTers(item) {
      this.sendText = item;
      this.showCommonTerms = false;
      this.inputFocus = true;
      this.handleLinechange({
        lineCount: 3,
      });
    },

    handleSendFile() {
      // #ifdef MP-WEIXIN
      let opt = {
        count: 1,
        type: "file",
        extension: ["doc", "docx", "xlsx", "pptx", "pdf"],
        success: (res) => {
          this.sendFile(res);

          // const tempFilePath = res.tempFiles[0].path;
          // const fileName = res.tempFiles[0].name;
          // uni.uploadFile({
          //   url: uploadAction,
          //   filePath: tempFilePath,
          //   name: "file",
          //   success: (fileRes) => {
          //     if (fileRes.data) {
          //       let filePath = "https://img106.job1001.com/" + fileRes.data;
          //       this.sendFile(filePath, fileName);
          //     }
          //   },
          //   fail: (err) => {
          //     uni.showToast({
          //       icon: "none",
          //       title: "文件发送失败",
          //     });
          //   },
          // });
        },
        fail: () => {
          uni.showToast({
            title: "文件选择失败",
            icon: "none",
          });
        },
      };
      wx.chooseMessageFile(opt);
      // #endif
    },
    sendFile(res) {
      const message = this.chat.createFileMessage({
        to: this.chatId,
        conversationType: TencentCloudChat.TYPES.CONV_C2C,
        payload: { file: res },
        onProgress: function(event) { console.log('file uploading:', event) }
      });
      this.createMsgContent(message);
      this.moreSendVisible = false;
      // let content = {
      //   send_uid: this.selfInfo.uname,
      //   receive_uid: this.chatId,
      //   content: "文件",
      //   share: {
      //     type: 100,
      //     slave: {
      //       name: fileName,
      //       path: filePath,
      //     },
      //   },
      //   person_iname: this.selfInfo.nickname,
      //   person_pic: this.selfInfo.pic,
      //   is_send: "1",
      //   idate: new Date().getTime(),
      // };
    },

    handleFileClick(file) {
      uni.navigateTo({
        url:
          "/pagesSub/public/file/index?name=" +
          file.fileName +
          "&path=" +
          encodeURIComponent(file.fileUrl),
      });
    },
    handleAdviserRole() {
      this.showRole = !this.showRole;
      if (this.showRole) {
        this.isShowAction = true;
      } else {
        this.isShowAction = false;
      }
    },
    sendDefaultAdviserMsg() {
      // 顾问首次打招呼
      let msg = `你好！我是${this.adviser.nickName}，关于${this.adviser.role}方面的问题可与我沟通咨询。`;
      let content = JSON.stringify({
        send_uid: this.adviser.username,
        receive_uid: this.selfInfo.uname,
        content: msg,
        person_iname: this.adviser.nickName,
        person_pic: this.adviser.avatar,
        is_send: "1",
        idate: new Date().getTime(),
        type: 1,
      });

      const params = {
        targetId: this.selfInfo.uname,
        fromId: this.adviser.username,
        content: content,
      };
      sendSingleTextMessage(params).then((res) => {});
    },
    // 极光错误上报
    reportImLog(data) {
      const params = {
        errorMessage: data,
      };
      reportImLog(params);
    },
    getConversationId() {
      const params = {
        fromAccount: this.selfInfo.uname,
        targetAccount: this.chatId,
      };
      return chatConversationCheck(params).then(res => {
        if (res.code === 200) {
          this.conversationId = res.data.conversationId;
        }
        return res
      })
    },
  },
};
</script>

<style lang="scss">
$img-base-message: $img-base + "message/";
.nav-job {
  font-size: $uni-font-size-min;
  color: $uni-text-color-666;
}

.adviser-title {
  font-weight: bold;
  font-size: 36rpx;

  .adviser-role {
    display: inline-block;
    font-size: 30rpx;
    font-weight: normal;
    margin-left: 12rpx;
    color: #222222;

    .u-icon {
      margin-left: 10rpx;
    }
  }
}

.chat {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  height: 1rpx;

  .chat-list {
    flex-grow: 1;
    height: 1rpx;
    ::v-deep .u-load-more-wrap {
      padding: 84rpx 0 12rpx;
    }
    .chat-item {
      margin: 32rpx;
      &:first-of-type {
        margin-top: 0;
      }
      &:last-of-type {
        padding-bottom: 32rpx;
      }
      .item-time {
        margin-bottom: 24rpx;
        color: $uni-text-color-888;
        text-align: center;
      }
      .item-content {
        position: relative;
        // padding: 32rpx;
        padding: 22rpx;
        max-width: calc(100% - 120rpx);
        font-size: $uni-font-size-nor;
        line-height: $uni-font-size-big;
        border-radius: 24rpx;
        box-sizing: border-box;
        white-space: pre-wrap;
        word-break: break-word;

        &.image {
          image {
            width: 240rpx;
            // max-height: 270rpx;
            // height: auto;
            // min-height: 274rpx;
            // box-sizing: border-box;
          }
        }
        &.other {
          display: flex;
          flex-direction: column;
          align-items: center;
          .cont-title {
            margin-top: 16rpx;
            font-size: $uni-font-size-lg;
          }
          .cont-tips {
            margin-top: 8rpx;
            font-size: $uni-font-size-nor;
            opacity: 0.8;
          }
        }
        &::after {
          content: "";
          display: block;
          position: absolute;
          top: 28rpx;
          width: 0;
          height: 0;
          border: 16rpx solid transparent;
        }
      }
      .other-tips {
        text-align: center;
        margin-bottom: $uni-spacing-row-lg;
        &-text {
          padding: 6rpx 32rpx;
          font-size: 24rpx;
          color: #999999;
          background-color: #efefef;
          border-radius: 28rpx;
        }

        .exchange-box {
          margin: 0 auto;
          width: 400rpx;
          padding: 30rpx;
          padding-bottom: 20rpx;
          background-color: $uni-bg-color;
          border-radius: $uni-border-radius-lg;
          &-title {
            padding: 20rpx 0;
            border-bottom: 2rpx solid $uni-text-color-grey;
          }
          &-disable {
            .btn {
              color: $uni-text-color-888;
            }
          }
          .btn {
            padding: 10rpx 20rpx;
            margin-top: 20rpx;
            display: inline-block;
            width: 160rpx;
            line-height: inherit;
            border-radius: 0;
            &:last-of-type {
              border-left: 2rpx solid $uni-text-color-grey;
            }
          }
        }
      }

      .item-opp {
        display: flex;
        justify-content: flex-start;
        padding-right: 54rpx;
        box-sizing: border-box;
        .item-content {
          margin-left: 16rpx;
          background: $uni-bg-color;
          border-top-left-radius: 0;
          &.image {
            padding: 0;
            background-color: transparent;
          }
          &.item-file {
            background: linear-gradient(180deg, #fff6ee 0%, #ffffff 100%);
          }
        }
      }
      .item-self {
        display: flex;
        justify-content: flex-end;
        padding-left: 54rpx;
        box-sizing: border-box;
        .read-status {
          flex-shrink: 0;
          align-self: center;
          margin-right: 8rpx;
          color: $uni-text-color-999;
          font-size: $uni-font-size-sm;
        }
        .item-content {
          margin-right: 16rpx;
          background: $bg-color-primary-light;
          border-top-right-radius: 0;
          &.image {
            padding: 0;
            background-color: transparent;
          }
          &.image::after {
            display: none;
          }
          &.item-file {
            background: linear-gradient(180deg, #fff6ee 0%, #ffffff 100%);
          }
        }
      }
      .item-avatar {
        flex-shrink: 0;
        width: 88rpx;
        height: 88rpx;
        border-radius: 50%;
        border: 1rpx solid $uni-bg-color-border;
        overflow: hidden;
        box-sizing: border-box;
      }
      .item-resume {
        display: flex;
        justify-content: space-between;
        .resume-text {
          display: inline-block;
          font-size: $uni-font-size-sm;
          color: $uni-text-color-999;
          .name {
            display: block;
            margin-bottom: 16rpx;
            font-size: $uni-font-size-lg;
            font-weight: bold;
            color: #000000;
          }
        }
        .icon-resume {
          margin-left: 80rpx;
          width: 66rpx;
          height: 88rpx;
          background-image: url($img-base-message + "resume.png");
          vertical-align: baseline;
        }
      }
      .item-file {
        display: flex;
        align-items: center;
        .icon-file {
          flex-shrink: 0;
          width: 96rpx;
          height: 94rpx;
          margin-right: 22rpx;
          background-image: url($img-base-message + "file.png");
        }
        .file-name {
          flex-grow: 1;
          color: #e8870d;
          font-size: 26rpx;
          line-height: 40rpx;
          max-height: 80rpx;
        }
      }
    }
  }

  .chat-send-wrap {
    flex-shrink: 0;
    background-color: #fff;
  }

  .chat-send {
    display: flex;
    justify-content: space-between;
    padding: 24rpx 32rpx 0 32rpx;
    background: $uni-bg-color;
    .icon {
      margin-top: 20rpx;
      width: 44rpx;
      height: 44rpx;
      background-size: 100% 100%;
      background-size: 100% 100%;
    }
    .icon-emoji {
      margin-right: 20rpx;
      background-image: url($img-base-message + "emoji.png");
    }
    .icon-keyboard {
      margin-right: 20rpx;
      background-image: url($img-base-message + "keyboard.png");
    }
    .icon-add {
      background-image: url($img-base-message + "add.png");
    }
    .icon-image {
      background-image: url($img-base-message + "image.png");
    }
    ::v-deep .chat-input {
      flex-grow: 1;
      flex-shrink: 1;
      display: flex;
      align-items: center;
      position: relative;
      margin-right: 24rpx;
      height: 88rpx;
      border-radius: 44rpx;
      background: $uni-bg-color-grey;
      overflow: auto;
      &.lines1 {
        height: 140rpx;
        textarea {
          height: 140rpx;
        }
      }
      &.lines2 {
        height: 180rpx;
        textarea {
          height: 180rpx;
        }
      }
      textarea {
        padding: 24rpx 32rpx;
        height: 88rpx;
        line-height: $uni-font-size-sec;
        font-size: $uni-font-size-base;
        &.clear {
          padding: 24rpx 0 24rpx 32rpx;
        }
      }
      .clear-icon {
        display: flex;
        align-items: center;
        padding: 0 24rpx;
        height: 100%;
      }
    }
    ::v-deep u-button {
      flex-shrink: 0;
    }
    ::v-deep button {
      flex-shrink: 0;
      width: 88rpx;
      height: 88rpx;
      border-radius: 50% !important;
      font-size: $uni-font-size-sm;
    }
    &-left {
      margin: 20rpx 32rpx 0 0;
      .icon {
        margin: 0;
      }
    }
    .btn-common-terms {
      width: 94rpx;
      color: #fff;
      font-size: 22rpx;
      line-height: 44rpx;
      background-color: #f75a3e;
      border-radius: 4rpx;
    }
  }
  .icon-send {
    width: 44rpx;
    height: 44rpx;
    background-image: url($img-base-message + "send.png");
    background-size: 100% 100%;
  }
  .icon-img {
    width: 80rpx;
    height: 80rpx;
    background-image: url($img-base-message + "img.png");
    background-size: 100% 100%;
  }
  .icon-file-fill {
    width: 80rpx;
    height: 80rpx;
    background-image: url($img-base-message + "file-fill.png");
    background-size: 100% 100%;
  }
  .more-send {
    display: flex;
    flex-wrap: wrap;
    background-color: #fff;
    padding: 24rpx 32rpx;
    &-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      width: 125rpx;
      color: $uni-text-color-666;
      font-size: $uni-font-size-sm;
      width: 25%;
      .img {
        width: 124rpx;
        height: 124rpx;
        margin: 28rpx 0 14rpx;
      }
    }
  }
  .face-scroll {
    height: 300rpx;
    padding-top: 20rpx;
    .face-wrap {
      display: flex;
      flex-wrap: wrap;
      padding-left: 10rpx;
      .face-item {
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: pointer;
        overflow: hidden;
        margin: -2rpx 0 0 -2rpx;
        padding: 8rpx 4rpx;
        text-align: center;
        height: 84rpx;
        width: 84rpx;
        // border: 2rpx solid #e8e8e8;
        &-img {
          width: 48rpx;
          height: 48rpx;
        }
      }
    }
  }
  .communication-position {
    margin-top: 16rpx;
    padding-top: 16rpx;
    border-top: 2px solid #eee;
  }
}
</style>
